package com.tiantian.lianhui.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiantian.lianhui.admin.domain.dto.req.ShortLinkGroupSortReqDTO;
import com.tiantian.lianhui.admin.domain.dto.req.ShortLinkGroupUpdateReqDTO;
import com.tiantian.lianhui.admin.domain.dto.resp.ShortLinkGroupRespDTO;
import com.tiantian.lianhui.admin.domain.entity.GroupEntity;
import com.tiantian.lianhui.admin.domain.entity.GroupUniqueEntity;
import com.tiantian.lianhui.admin.mapper.GroupMapper;
import com.tiantian.lianhui.admin.mapper.GroupUniqueMapper;
import com.tiantian.lianhui.admin.service.GroupService;
import com.tiantian.lianhui.admin.toolkit.RandomGenerator;
import com.tiantian.lianhui.common.biz.user.UserContext;
import com.tiantian.lianhui.common.convention.exception.ClientException;
import com.tiantian.lianhui.common.convention.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.tiantian.lianhui.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;


/**
 * 短链接分组接口实现层

 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupEntity> implements GroupService {

    private final RBloomFilter<String> gidRegisterCachePenetrationBloomFilter;
    private final GroupUniqueMapper groupUniqueMapper;
    private final GroupMapper baseMapper;
    // private final ShortLinkActualRemoteService shortLinkActualRemoteService;
    private final RedissonClient redissonClient;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(String groupName) {
        saveGroup(UserContext.getUsername(), groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
        lock.lock();
        try {
            LambdaQueryWrapper<GroupEntity> queryWrapper = Wrappers.lambdaQuery(GroupEntity.class)
                    .eq(GroupEntity::getUsername, username)
                    .eq(GroupEntity::getDelFlag, 0);
            List<GroupEntity> groupDOList = baseMapper.selectList(queryWrapper);
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum) {
                throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
            }
            int retryCount = 0;
            int maxRetries = 10;
            String gid = null;
            while (retryCount < maxRetries) {
                gid = saveGroupUniqueReturnGid();
                if (StrUtil.isNotEmpty(gid)) {
                    GroupEntity groupDO = GroupEntity.builder()
                            .gid(gid)
                            .sortOrder(0)
                            .username(username)
                            .name(groupName)
                            .build();
                    baseMapper.insert(groupDO);
                    gidRegisterCachePenetrationBloomFilter.add(gid);
                    break;
                }
                retryCount++;
            }
            if (StrUtil.isEmpty(gid)) {
                throw new ServiceException("生成分组标识频繁");
            }
        } finally {
            lock.unlock();
        }
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupEntity> queryWrapper = Wrappers.lambdaQuery(GroupEntity.class)
                .eq(GroupEntity::getUsername, UserContext.getUsername())
                .eq(GroupEntity::getDelFlag, 0)
                .orderByDesc(GroupEntity::getSortOrder, GroupEntity::getSortOrder);
        List<GroupEntity> groupEntityList = baseMapper.selectList(queryWrapper);
        return BeanUtil.copyToList(groupEntityList, ShortLinkGroupRespDTO.class);
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        String username = UserContext.getUsername();
        LambdaUpdateWrapper<GroupEntity> updateWrapper = Wrappers.lambdaUpdate(GroupEntity.class)
                .eq(GroupEntity::getUsername, username)
                .eq(GroupEntity::getGid, requestParam.getGid())
                .eq(GroupEntity::getDelFlag, 0);
        GroupEntity groupEntity = new GroupEntity();

        groupEntity.setGid(requestParam.getGid());
        groupEntity.setName(requestParam.getName());
        baseMapper.update(groupEntity, updateWrapper);
    }

    @Override
    public void deleteGroup(String gid) {
        LambdaUpdateWrapper<GroupEntity> updateWrapper = Wrappers.lambdaUpdate(GroupEntity.class)
                .eq(GroupEntity::getUsername, UserContext.getUsername())
                .eq(GroupEntity::getGid, gid)
                .eq(GroupEntity::getDelFlag, 0);
        GroupEntity groupEntity = new GroupEntity();
        groupEntity.setDelFlag(1);
        baseMapper.update(groupEntity, updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {
            GroupEntity groupDO = GroupEntity.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            LambdaUpdateWrapper<GroupEntity> updateWrapper = Wrappers.lambdaUpdate(GroupEntity.class)
                    .eq(GroupEntity::getUsername, UserContext.getUsername())
                    .eq(GroupEntity::getGid, each.getGid())
                    .eq(GroupEntity::getDelFlag, 0);
            baseMapper.update(groupDO, updateWrapper);
        });
    }

    private String saveGroupUniqueReturnGid() {
        String gid = RandomGenerator.generateRandom();
        if (!gidRegisterCachePenetrationBloomFilter.contains(gid)) {
            GroupUniqueEntity groupUniqueEntity = GroupUniqueEntity.builder()
                    .gid(gid)
                    .build();
            try {
                groupUniqueMapper.insert(groupUniqueEntity);
            } catch (DuplicateKeyException e) {
                return null;
            }
        }
        return gid;
    }
}
